package com.wbao.dianniu.service;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.wbao.dianniu.data.SyncInfoData;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.tabstrip.fragments.FourthFragment;
import com.wbao.dianniu.tabstrip.fragments.NotifyFragment;
import com.wbao.dianniu.update.ScoreChangeManager;
import com.wbao.dianniu.utils.JsonUtil;

import java.util.List;

/**
 * Created by yejianjun on 2018/5/25.
 * <p>
 * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */

public class DemoIntentService extends GTIntentService {
    private static final String TAG = "DemoIntentService";

    public DemoIntentService() {
    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
//        Log.d(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        // 保存clientId
        SharedPreferencesUtils.setClientId(context, clientid);
//        Log.d(TAG, "onReceiveClientId -> clientid: " + clientid);
    }

    // 透传消息到达
    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage gtTransmitMessage) {
        byte[] bt = gtTransmitMessage.getPayload();
        String content = new String(bt);
        /*System.out.println("onReceiveMessageData.........id:" + gtTransmitMessage.getMessageId() +
                "  payloadId: " + gtTransmitMessage.getPayloadId() + " taskId:" + gtTransmitMessage.getTaskId()
                + "  str:" + content);*/

        sendScoreBroadcast(content);
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean b) {
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage gtCmdMessage) {
    }

    // 通知消息到达
    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage gtNotificationMessage) {
        sendUIBroadcast();
    }

    // 通知消息点击
    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage gtNotificationMessage) {
        if (isBackground()) {
            // 在后台运行
            startAPP("com.wbao.dianniu");
        } else {

        }
    }

    public void startAPP(String appPackageName) {
        try {
            Intent intent = this.getPackageManager().getLaunchIntentForPackage(appPackageName);
            startActivity(intent);
        } catch (Exception e) {
//            Toast.makeText(this, "没有安装", Toast.LENGTH_LONG).show();
        }
    }

    //通过判断手机里的所有进程是否有这个App的进程
    //从而判断该App是否有打开
    private boolean isBackground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(this.getPackageName())) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(this.getPackageName(), "处于后台" + appProcess.processName);
                    return true;
                } else {
                    Log.i(this.getPackageName(), "处于前台" + appProcess.processName);
                    return false;
                }
            }
        }
        return false;

    }

    /**
     * 发送通知刷新广播
     */
    private void sendUIBroadcast() {
        Intent intent = new Intent();//创建Intent对象
        intent.setAction(NotifyFragment.ACTION_UPDATEUI);
        sendBroadcast(intent);//发送广播
    }

    /**
     * 发送积分更新广播
     */
    private void sendScoreBroadcast(String content) {
        processContent(content);
        Intent intent = new Intent();//创建Intent对象
        intent.setAction(FourthFragment.ACTION_SCORE_UPDATE);
        intent.putExtra(FourthFragment.INTENT_DATA, content);
        sendBroadcast(intent);//发送广播
    }

    /**
     * 收到积分后 先保存到数据库，再通知，防止积分收到时，界面还没加载完成，通知不到的情况...
     *
     * @param content
     */
    private void processContent(String content) {
        SyncInfoData syncData = JsonUtil.toObject(content, SyncInfoData.class);
        if (null != syncData && null != syncData.action) {
            GlobalUserData userData = new GlobalUserData();
            if (syncData.action.equals(Const.SyncInsturyKey)) {
                if (null != syncData.args.getAsJsonObject().get(Const.SyncInsturyValue)) {
                    GlobalContext.setIndustryAuthority(syncData.args.getAsJsonObject().get(Const.SyncInsturyValue).getAsBoolean());
                }
                if (null != syncData.args.getAsJsonObject().get(Const.SyncScoreValue)) {
                    int score = userData.getScore();
                    score = score + syncData.args.getAsJsonObject().get(Const.SyncScoreValue).getAsInt();
                    userData.setScore(score);
                }
            } else if (syncData.action.equals(Const.SyncScoreKey)) {
                if (null != syncData.args.getAsJsonObject().get(Const.SyncScoreValue)) {
                    int score = userData.getScore();
                    score = score + syncData.args.getAsJsonObject().get(Const.SyncScoreValue).getAsInt();
                    userData.setScore(score);
                }
            } else if (syncData.action.equals(Const.updatePartnerTarget)) {
                if (null != syncData.args.getAsJsonObject().get(Const.partner)) {
                    int partner = syncData.args.getAsJsonObject().get(Const.partner).getAsInt();
                    userData.setPartner(partner);
                }
            }
        }
    }

}
